from pathlib import PurePath
from typing import Literal, List

from fastapi import Depends, BackgroundTasks, Request
from fastapi.responses import RedirectResponse
from pydantic import BaseModel

from .config import app_setting
from .dependency import resource_creator_router
from .resource_model.client_115.schemas import FileOrFolder
from .resource_model.drive_115.dependency import get_operate_layer, OperateLayer
from .webdav_router import WebDavRouter

router = WebDavRouter()


# schema
class QueryPathIn(BaseModel):
    path: str
    depth: Literal[0, 1]


class QueryDownloadInfoIn(BaseModel):
    pickcode: str


class RedirectItem(BaseModel):
    a: str


# 以下为测试接口
@router.post("/refresh")
async def refresh_data(bck_task: BackgroundTasks, op_layer: OperateLayer = Depends(get_operate_layer)):
    bck_task.add_task(op_layer.refresh_cache, "789862890424388006", PurePath("/dav_115"))
    return {"status": "success"}


@router.post("/query115Path", response_model=List[FileOrFolder])
async def query_115_path(
        query_in: QueryPathIn, op_layer: OperateLayer = Depends(get_operate_layer)
):
    path = PurePath(query_in.path)
    res = await op_layer.search_until_find(path, query_in.depth, app_setting.PAN_115_MOUNT_PATH)
    return res


@router.post("/redirect_target")
async def redirect_target(request: Request, item: RedirectItem):
    print(request.method)
    print(request.cookies)
    return item


@router.post("/redirect_resp")
async def redirect_resp(item: RedirectItem):
    _ = item
    url = router.url_path_for("redirect_target")
    resp = RedirectResponse(url)
    resp.set_cookie("new_k", "new_val")
    return resp


@router.post("/downloadInfo")
async def query_by_pickcode(query_in: QueryDownloadInfoIn,
                            op_layer: OperateLayer = Depends(get_operate_layer)):
    client = op_layer.client
    res = await client.get_download_info(query_in.pickcode)
    return res.dict()


@router.post("/{any_path:path}")
async def query_path(request: Request, creator=Depends(resource_creator_router)):
    dr = await creator.put_file(request)
    return dr
